package hc.j2me.ui;

import hc.core.ContextManager;
import hc.core.MsgBuilder;
import hc.core.data.DataSelectTxt;
import hc.j2me.ScreenClientManager;
import hc.j2me.util.ImageUtility;

import java.io.IOException;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Layer;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;

public class PosMVC {
	private Sprite posLeft, posRight, selectArea, arrowPanel, userSelectedMenu;
	private final LayerManager lm;
	private HCCtrlGameCanvas gamecanvas;
	private int[] imgData;
	private int remoteX, remoteY, startX, startY, endX, endY;
	private int _16, _blockWidth, userMouseSplitWidth, upSideColor, downSideColor, backgroundColor;
	private boolean isOn = false, isLeftRelaArrawPanel = false;
	private final byte[] pointDragBS = new byte[DataSelectTxt.STRUCT_LEN + MsgBuilder.INDEX_MSG_DATA]; 
	
	private static void fillCellBox(final int cellX, final int cellY, final int cellWidth, final int cellHeight, 
			final int color, final int width, final int[] array){
		final int x1 = cellX * cellWidth;
		final int y1 = cellY * cellHeight;
		ImageUtility.fillBox(x1, y1, x1 + cellWidth, y1 + cellHeight - 1, color, width, array);
	}

	private Image createArrowPanel(final int _16, final int _blockWidth, final int userMouseSplitWidth,
			final int upSideColor, final int downSideColor, final int backgroundColor){
		final int[] array = new int[_blockWidth * _blockWidth * 9];
		final int width = _blockWidth * 3;
		final int[] arrayX = {1, 0, 1, 2, 1};
		final int[] arrayY = {0, 1, 1, 1, 2};
		final String[] imgURLs = {
				"uparrow_" + _16 + ".png",
				"leftarrow_" + _16 + ".png",
				"ok_" + _16 + ".png",
				"rightarrow_" + _16 + ".png",
				"downarrow_" + _16 + ".png"};
		final int[] imgdata = new int[_16 * _16];
		for (int i = 0; i < arrayX.length; i++) {
			final int cellX = arrayX[i];
			final int cellY = arrayY[i];
			fillCellBox(cellX, cellY, _blockWidth, _blockWidth, backgroundColor, width, array);
			ImageUtility.drawBoxAtCell(width, array, cellX, cellY, _blockWidth, userMouseSplitWidth, _16, upSideColor, downSideColor);
			final String imgURL = "/hc/j2me/res/" + imgURLs[i];
			Image img;
			try {
				img = Image.createImage(imgURL);
				img.getRGB(imgdata, 0, _16, 0, 0, _16, _16);
				final int tx = cellX * (_blockWidth) + userMouseSplitWidth;
				final int ty = cellY * (_blockWidth) + userMouseSplitWidth;
				ImageUtility.drawImage(imgdata, 0, 0, _16, _16, _16, _16, true, tx, ty, width, array);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return ImageUtility.createSafeAlphaImg(array, width, width, array.length, ImageUtility.isHardAlpha);
	}
	
	PosMVC(HCCtrlGameCanvas gc, LayerManager lm, Layer overLayer, Sprite userSelectedMenu,
			int _16, int _blockWidth, int userMouseSplitWidth, int upSideColor, int downSideColor, int backgroundColor){
		this.gamecanvas = gc;
		this.lm = lm;
		this._16 = _16;
		this._blockWidth = _blockWidth;
		this.userMouseSplitWidth = userMouseSplitWidth;
		this.upSideColor = upSideColor;
		this.downSideColor = downSideColor;
		this.backgroundColor = backgroundColor;
		this.userSelectedMenu = userSelectedMenu;
		
		Image posImg = null;
		try {
			posImg = Image.createImage("/hc/j2me/res/pos.png");
		} catch (IOException e) {
			e.printStackTrace();
		}
		posLeft = new Sprite(posImg);
		posRight = new Sprite(posImg);
		
		final int idx = PNGGameCanvas.getLayerIdx(lm, overLayer);
		lm.insert(posLeft, idx);
		lm.insert(posRight, idx);

	}
	
	public void setInitPos(int remoteX, int remoteY, final int startX, final int startY, final int endX, final int endY){
		isOn = true;
		gamecanvas.showMouseOp(false);
		userSelectedMenu.setVisible(false);
		
		this.remoteX = remoteX;
		this.remoteY = remoteY;
		this.startX = startX;
		this.startY = startY;
		this.endX = endX;
		this.endY = endY;
		
//		L.V = L.O ? false : LogManager.log("remoteX : " + remoteX + ", remoteY : " + remoteY
//				+ " startX : " + startX + ", startY : " + startY
//				+ " endX : " + endX + ", endY : " + endY);
		
		posLeft.setVisible(true);
		posRight.setVisible(true);
		posLeft.setPosition(startX - posLeft.getWidth() / 2, startY);
		posRight.setPosition(endX - posLeft.getWidth() / 2 + 1, endY + 1);		

		final int areaWidth = Math.abs((posRight.getX() - posLeft.getX()));
		final int areaHeight = Math.abs((posRight.getY() - posLeft.getY()));
		
		final int areaNum = areaWidth * areaHeight;
		final int areaArrNum = (areaNum / 1024 + 1) * 1024;
		if(imgData == null || imgData.length < areaArrNum){
			imgData = new int[areaArrNum];
		}
		for (int i = 0; i < areaNum; i++) {
			imgData[i] = ImageUtility.LIGHT_SELECT_AREA;
		}
		ImageUtility.drawBox(0, 0, areaWidth-1, areaHeight-1, ImageUtility.downSideColor, ImageUtility.downSideColor, areaWidth, imgData);
		Image area = ImageUtility.createSafeAlphaImg(imgData, areaWidth, areaHeight, areaNum, true);
		if(selectArea == null){
			selectArea = new Sprite(area);
			lm.insert(selectArea, PNGGameCanvas.getLayerIdx(lm, posLeft) + 1);//+1,是置于后
		}else{
			selectArea.setImage(area, areaWidth, areaHeight);
			selectArea.setVisible(true);
		}
		selectArea.setPosition((startX < endX)?startX:endX, (startY < endY)?startY:endY);
	}
	
	public boolean isOnMode(){
		return isOn;
	}
	
	public int pointerDragged(final int startX, final int startY, 
			final int endX, final int endY, final int x, final int y) {
		return 0;
	}
	
	public int pointerReleased(final int x, final int y) {
		boolean isOnLeft;
		if((isOnLeft = isOnPos(posLeft, x, y)) || isOnPos(posRight, x, y)){
			iniArrayPanel();
			final int centerX = ScreenClientManager.getClientWidth()/2;
			final int centerY = ScreenClientManager.getClientHeight()/2;
			int apX, apY;
			int pLeftX = posLeft.getX(), pRightX = posRight.getX();//, pLeftY = posLeft.getY(), pRightY = posRight.getY();
			if(x <= centerX){
				apX = ((pLeftX<pRightX)?pLeftX:pRightX) + posLeft.getWidth()/2;
			}else{
				apX = ((pLeftX>pRightX)?pLeftX:pRightX) - arrowPanel.getWidth() + posLeft.getWidth()/2;
			}
			if(y <= centerY){
				apY = y + posLeft.getHeight() + 10;
			}else{
				apY = y - posLeft.getHeight() - arrowPanel.getHeight();
			}
			arrowPanel.setPosition(apX, apY);
			if(arrowPanel.collidesWith(posRight, false)){
				arrowPanel.setPosition(
						apX - arrowPanel.getWidth() * ((apX > centerX)?1:-1), 
						apY - arrowPanel.getHeight() * ((apY > centerY)?1:-1));
			}
			isLeftRelaArrawPanel = isOnLeft;
//			userSelectedMenu.setVisible(false);
			return HCCtrlGameCanvas.R_OK;
		}
		
		if(arrowPanel != null && arrowPanel.isVisible()){
			//点击中间的OK
			final int apX = arrowPanel.getX();
			final int apY = arrowPanel.getY();
			
			if(y > apY && y < apY + arrowPanel.getHeight()
					&& x > apX && x < apX + arrowPanel.getWidth()){
				final int oneblockY = apY + _blockWidth;
				final int oneblockX = apX + _blockWidth;
				final int twoblockX = apX + _blockWidth * 2;
				if(y < oneblockY){
					if(x < oneblockX){
						return HCCtrlGameCanvas.R_ERR;
					}else if(x < twoblockX){
						userSelectedMenu.setPosition(oneblockX + userMouseSplitWidth, apY + userMouseSplitWidth);
						return move(UP_MOVE, isLeftRelaArrawPanel);
					}else{
						return HCCtrlGameCanvas.R_ERR;
					}
				} else {
					final int twoblockY = apY + _blockWidth * 2;
					if(y < twoblockY){
						if(x < oneblockX){
							userSelectedMenu.setPosition(apX + userMouseSplitWidth, oneblockY + userMouseSplitWidth);
							return move(LEFT_MOVE, isLeftRelaArrawPanel);
						}else if(x < twoblockX){
//							userSelectedMenu.setPosition(oneblockX + userMouseSplitWidth, oneblockY + userMouseSplitWidth);
							endSelectArea();
							return HCCtrlGameCanvas.R_OK;
						}else{
							userSelectedMenu.setPosition(twoblockX + userMouseSplitWidth, oneblockY + userMouseSplitWidth);
							return move(RIGHT_MOVE, isLeftRelaArrawPanel);
						}
					}else{
						if(x < oneblockX){
							return HCCtrlGameCanvas.R_ERR;
						}else if(x < twoblockX){
							userSelectedMenu.setPosition(oneblockX + userMouseSplitWidth, twoblockY + userMouseSplitWidth);
							return move(DOWN_MOVE, isLeftRelaArrawPanel);
						}else{
							return HCCtrlGameCanvas.R_ERR;
						}
					}
				}
			}
		}
		
		if(x >= selectArea.getX() && x < (selectArea.getX() + selectArea.getWidth())
				&& y >= selectArea.getY() && y < (selectArea.getY() + selectArea.getHeight())){
			endSelectArea();
			return HCCtrlGameCanvas.R_OK;
		}
		
		return HCCtrlGameCanvas.R_ERR;
	}
	
	public static final int UP_MOVE = 1, LEFT_MOVE = 2, RIGHT_MOVE = 3, DOWN_MOVE = 4; 
	private int move(final int move, final boolean isLeft){
		userSelectedMenu.setVisible(true);
		
		final int move_step = 1;
		final int startxM = (isLeft?
				((move == LEFT_MOVE)?
						(-1*move_step)
						:(move == RIGHT_MOVE)?
								move_step:0):0);
		final int startyM = (isLeft?
				((move == UP_MOVE)?
						(-1*move_step)
						:(move == DOWN_MOVE)?
								move_step:0):0);
		final int endxM = ((!isLeft)?
				((move == LEFT_MOVE)?
						(-1*move_step)
						:(move == RIGHT_MOVE)?
								move_step:0):0);
		final int endyM = ((!isLeft)?
				((move == UP_MOVE)?
						(-1*move_step)
						:(move == DOWN_MOVE)?
								move_step:0):0);
		setInitPos(
				remoteX + startxM, 
					remoteY + startyM, 
				startX + startxM, 
					startY + startyM, 
				endX + endxM, 
					endY + endyM);
		return HCCtrlGameCanvas.R_OK;
	}
	
	private void endSelectArea(){
		sendAreaInfo();

		posLeft.setVisible(false);
		posRight.setVisible(false);
		selectArea.setVisible(false);
		if(arrowPanel != null){
			arrowPanel.setVisible(false);
		}
		userSelectedMenu.setVisible(false);
		isOn = false;
		
		gamecanvas.showMouseOp(true);
	}

	private void iniArrayPanel() {
		if(arrowPanel == null){
			arrowPanel = new Sprite(createArrowPanel(
					_16, _blockWidth, userMouseSplitWidth, upSideColor, downSideColor, backgroundColor));
			lm.insert(arrowPanel, PNGGameCanvas.getLayerIdx(lm, posLeft));
		}else{
			if(arrowPanel.isVisible() == false){
				arrowPanel.setVisible(true);
			}
		}
	}
	
	private boolean isOnPos(final Sprite pos, final int px, final int py){
		final int x = pos.getX() + pos.getWidth() / 2;
		final int y = pos.getY() + pos.getHeight() / 2;
		
		if(px >= (x - 16) && px <= (x + 16) && py >= (y - 16) && (py <= (y + 16))){
			return true;
		}else{
			return false;
		}
	}
	
	public void sendAreaInfo(){
		// 进入选择远程机器的文本方式

		DataSelectTxt st = new DataSelectTxt();
		st.setBytes(pointDragBS);

		st.setStartX(remoteX);
		st.setStartY(remoteY);
		st.setEndX(remoteX + (posRight.getX() - posLeft.getX()));
		st.setEndY(remoteY + (posRight.getY() - posLeft.getY()));

		ContextManager.getContextInstance().send(
				MsgBuilder.E_SCREEN_SELECT_TXT, pointDragBS, st.getLength());
	}
}
